package com.epro.dx.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

import com.epro.dx.R;

/**
 * 波纹按钮
 * @author Zenglw
 * @version 1.0
 * @date 2017/7/19
 */

public class RippleButton extends Button {

    private Paint paint;
    //每次半径增加的值
    private int addValue ;

    //当前的半径值
    private int curValue;

    //水波纹的最大半径
    private int MAX_VALUE;

    private float centerX;

    private float centerY;

    private boolean isPaint;

    public RippleButton(Context context) {
        this(context,null);
    }

    public RippleButton(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RippleButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RippleButton);
        addValue = array.getInteger(R.styleable.RippleButton_rate, 20);
        array.recycle();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getResources().getColor(R.color.color_gray_light));
        paint.setAntiAlias(true);
        paint.setDither(true);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        MAX_VALUE = (int) Math.hypot(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        if (isPaint) {
            if (curValue <= MAX_VALUE) {
                canvas.drawCircle(centerX,centerY,curValue,paint);
                curValue += addValue;
            }
            invalidate();
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isPaint = true;
                curValue = 10;
                centerX = event.getX();
                centerY = event.getY();
                invalidate();
                break;

        }

        return super.onTouchEvent(event);
    }
}
